/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package slicktemplate;

import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayList;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.state.StateBasedGame;

/**
 *
 * @author Josh
 */
public class Turret extends Collideable implements Renderable, Updateable, Attackable,Serializable {

    float x, y;
    final int MAX_HEALTH = 300;
    public static final ArrayList<Turret> all = new ArrayList<Turret>();
    SerializableImage sprite;
    
    static final int reload = 30;
    long steps = 0;
    long lastFired = -reload;
    int health = MAX_HEALTH;
    Enemy1 nearest; //just for testing, will be remvoed later

    public Turret(float x, float y) {
        all.add(this);
        this.x = x;
        this.y = y;
        try {
            sprite =  new SerializableImage("sprites/turret.png"); //try to load the sprite
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        boundingBox = new Rectangle(x, y, sprite.getWidth() - 1, sprite.getHeight() - 1);
    }

    @Override
    public void render(Graphics g) {
        sprite.draw(x, y);
        g.setColor(Color.red);
        g.fillRect(x, y, sprite.getWidth(), 6);
        g.setColor(Color.green);
        g.fillRect(x, y, sprite.getWidth()*health/MAX_HEALTH, 6);
    }

    @Override
    public boolean update(Input input, StateBasedGame sb) {
        steps ++;
        nearest = null;
        if (!Enemy1.all.isEmpty()) {
            double smallest = Double.POSITIVE_INFINITY;
            for (Enemy1 it : Enemy1.all) {
                if (Point2D.distance(x, y, it.getX(), it.getY()) < smallest) {
                    nearest = it;
                    smallest = Point2D.distance(x, y, it.getX(), it.getY());
                }
            }
            int rotatedegrees = (int) ((int) (180 / Math.PI) * Math.atan2((nearest.getY() - y), (nearest.getX() - x)));
            sprite.setRotation(rotatedegrees);
            if(steps-lastFired > reload) {
                new ProjectileNail(x + 16, y + 16, 4, MathHelper.point_direction(x, y, nearest.x, nearest.y), 25, this);
                lastFired = steps;
            }
        }
        if(health <= 0) {
            return true;
        } 

        return false;
    }

    @Override
    public float getX() {
        return x;
    }

    @Override
    public float getY() {
        return y;
    }

    @Override
    public float getHealth() {
        return 0;
    }
     public void mousePressed(StateBasedGame sb, int button) {

    }

    @Override
    boolean isBuilding() {
        return true;
    }

    
     
    @Override
    public void subHealth(int hp) {
        health -= hp;
    }
}
